<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="100px">
        <el-form-item label="外部编号">
          <el-input
            v-model="searchParam.extenalCode"
            placeholder="请输入外部编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <div v-if="isExpanded">
          <el-form-item label="物料号">
            <el-input
              v-model="searchParam.materialCode"
              placeholder="请输入物料号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="包装物物料号">
            <el-input
              v-model="searchParam.packageMaterialCode"
              placeholder="请输入包装物物料号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="存储批次">
            <el-input
              v-model="searchParam.stockBatch"
              placeholder="请输入存储批次"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>
          <el-form-item label="供应批次">
            <el-input
              v-model="searchParam.supplyBatch"
              placeholder="请输入供应批次"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="公司编号">
            <el-input
              v-model="searchParam.organizationCode"
              placeholder="请输入公司编号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="工厂">
            <el-select
              v-model="searchParam.plantId"
              placeholder="请选择所在工厂"
              clearable
            >
              <el-option
                v-for="item in plantList"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="仓库号">
            <el-input
              v-model="searchParam.warehouseCode"
              placeholder="请输入仓库号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="存储地点编号">
            <el-input
              v-model="searchParam.storageLocationCode"
              placeholder="请输入存储地点编号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="存储类型号">
            <el-input
              v-model="searchParam.storageTypeCode"
              placeholder="请输入存储类型号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="存储区号">
            <el-input
              v-model="searchParam.storageSectionCode"
              placeholder="请输入存储区号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="仓位编号">
            <el-input
              v-model="searchParam.binCode"
              placeholder="请输入仓位编号"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchParam.createTimeSearch"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="getcreateTime"
            />
          </el-form-item>

          <el-form-item label="创建人">
            <el-input
              v-model="searchParam.createdUserName"
              placeholder="请输入创建人"
              clearable
              @keyup.enter="search"
            />
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" @click="search"
          ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
          <el-button
            class="ml-3"
            @click="
              useDownload(
                '/wms/storageunit/export',
                '包装库存',
                searchParam,
                true,
                '.xls'
              )
            "
          >
            <template #icon><i-ep-download /></template>导出</el-button
          >
          <el-button type="primary" @click="toggleSearchArea" link>
            {{ isExpanded ? "收起" : "展开" }}
            <el-icon v-if="isExpanded" class="el-icon--right">
              <i-ep-arrowUp color="#409EFC" />
            </el-icon>
            <el-icon v-else class="el-icon--right">
              <i-ep-arrowDown color="#409EFC" />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header> </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="外部编号" prop="extenalCode" min-width="150" />
        <el-table-column
          label="物料"
          prop="materialCode"
          min-width="160"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.materialCode }} - {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column label="采购订单号" prop="remarks" min-width="150" />
        <el-table-column
          label="包装物物料号"
          prop="packageMaterialCode"
          min-width="130"
        />
        <el-table-column
          label="包装物物料名称"
          prop="packageMaterialName"
          min-width="130"
        />
        <el-table-column label="存储批次" prop="stockBatch" min-width="100" />
        <el-table-column label="供应批次" prop="supplyBatch" min-width="150" />

        <el-table-column
          label="公司编号"
          prop="organizationCode"
          min-width="100"
        />
        <el-table-column
          label="公司名称"
          prop="organizationName"
          min-width="200"
        />

        <el-table-column label="工厂" prop="plantCode" width="100" />

        <el-table-column label="仓库号" prop="warehouseCode" min-width="100" />
        <el-table-column
          label="仓库名称"
          prop="warehouseName"
          min-width="200"
        />

        <el-table-column
          label="存储地点编号"
          prop="storageLocationCode"
          min-width="120"
        />
        <el-table-column
          label="存储地点名称"
          prop="storageLocationName"
          min-width="150"
        />

        <el-table-column
          label="存储类型号"
          prop="storageTypeCode"
          min-width="100"
        />
        <el-table-column
          label="存储类型名称"
          prop="storageTypeName"
          min-width="200"
        />

        <el-table-column
          label="存储区号"
          prop="storageSectionCode"
          min-width="100"
        />

        <el-table-column label="仓位编号" prop="binCode" min-width="120" />
        <el-table-column label="总数量" prop="totalQuantity" min-width="100" />
        <el-table-column
          label="可用数量"
          prop="availableQuantity"
          min-width="100"
        />
        <el-table-column
          label="限制使用数量"
          prop="freezeQuantity"
          min-width="120"
        />
        <el-table-column label="数量单位" prop="quantityUnit" min-width="100" />
        <el-table-column label="占用容积" prop="usedColume" min-width="100" />
        <el-table-column label="占用面积" prop="usedArea" min-width="100" />
        <el-table-column label="占用载重量" prop="usedWeight" min-width="100" />

        <!--<el-table-column label="备注" prop="remarks" min-width="300" />-->
        <el-table-column label="创建时间" prop="createTime" min-width="160" />

        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
        />
        <el-table-column
          label="修改时间"
          prop="lastUpdateTime"
          min-width="160"
        />

        <el-table-column
          label="修改人"
          prop="lastUpdatedUserName"
          min-width="100"
        />
        <el-table-column fixed="right" label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-edit />
              查看
            </el-button>
            <el-button
              style="color: #409eff"
              type="success"
              size="small"
              link
              @click="open(scope.row)"
            >
              打印
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <wmsstorageunitquery-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="reset"
      @change-visible="changeVisible"
    />
    <iframe
      v-if="showWebView"
      :src="webviewSrc"
      :update-title="false"
      style="width: 0; height: 0"
    ></iframe>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "WMSSTORAGEUNITQUERY",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/wms/storageunit/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {
  sort: {
    column: "last_update_time",
    orderBy: "desc",
  },
};
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
};
// 初始化搜索参数数据
const searchParamInit = {
  storageUnitCode: "",
  extenalCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  packageMaterialId: "",
  packageMaterialCode: "",
  packageMaterialName: "",
  stockBatch: "",
  supplyBatch: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  warehouseId: "",
  warehouseCode: "",
  warehouseName: "",
  storageLocationId: "",
  storageLocationCode: "",
  storageLocationName: "",
  storageTypeId: "",
  storageTypeCode: "",
  storageTypeName: "",
  storageSectionId: "",
  storageSectionCode: "",
  binId: "",
  binCode: "",
  totalQuantity: "",
  availableQuantity: "",
  freezeQuantity: "",
  quantityUnit: "",
  usedColume: "",
  usedArea: "",
  usedWeight: "",
  version: "",
  remarks: "",
  createTimeSearch: [],
  createTimeStart: "",
  createTimeEnd: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTimeSearch: [],
  lastUpdateTimeStart: "",
  lastUpdateTimeEnd: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};

const deleteParam = {
  api: "/wms/storageunit/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const isExpanded = ref(false);

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const addDialog = reactive<DialogOption>({
  visible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  const { data } = await request({
    url: `/wms/storageunit/getinfo/${id}`,
    method: "get",
  });
  addDialog.data = data;
}
function toggleSearchArea() {
  isExpanded.value = !isExpanded.value;
}

/** 打开包装单位表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "包装单位详情";
  getInfo(roleObj.id);
  addDialog.visible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  getTableList();
  inputAutoFocus();
  if (!value) {
    addDialog.data = {};
  }
}

function getcreateTime(data: any) {
  if (data) {
    searchParam.value.createTimeStart = data[0];
    searchParam.value.createTimeEnd = data[1];
  } else {
    searchParam.value.createTimeStart = "";
    searchParam.value.createTimeEnd = "";
  }
}
function getlastUpdateTime(data: any) {
  if (data) {
    searchParam.value.lastUpdateTimeStart = data[0];
    searchParam.value.lastUpdateTimeEnd = data[1];
  } else {
    searchParam.value.lastUpdateTimeStart = "";
    searchParam.value.lastUpdateTimeEnd = "";
  }
}

// 进入页面聚焦
const inputRef = ref();
const readonly = ref(true);
const inputAutoFocus = () => {
  nextTick(() => {
    readonly.value = true;
    inputRef.value.focus();
    setTimeout(() => {
      readonly.value = false;
    }, 0);
  });
};

// 触发打印
const IFRAME_URL = import.meta.env.VITE_APP_IFRAME_URL;
const showWebView = ref(false);
const webviewSrc = ref("");
const returnText = ref("");
function confirmImport(id: string, instance: any, done: Function) {
  returnText.value = "";
  webviewSrc.value = `${IFRAME_URL}iframePrintUnit?id=${id}`;
  console.log("webviewSrc.value", webviewSrc.value);
  showWebView.value = true;
  // 设置调用间隔，当打印机被初始化后，提醒用户打印中
  let sumTime = 0;
  let intervalId = setInterval((instance1 = instance, done1 = done) => {
    sumTime += 500;
    if (returnText.value.length) {
      instance1.confirmButtonLoading = false;
      showWebView.value = false;
      done1();
      ElMessage(returnText.value);
      clearInterval(intervalId);
    }
    if (sumTime >= 5000 && !returnText.value) {
      instance1.confirmButtonLoading = false;
      showWebView.value = false;
      done1();
      ElMessage.error("打印失败，请稍后再试");
      clearInterval(intervalId);
    }
  }, 500);
}
const open = (row) => {
  ElMessageBox.confirm(
    `当前外部编号为${row?.extenalCode ?? ""}, 请确认是否打印？`,
    "提示",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose: (action, instance, done) => {
        if (action === "confirm") {
          // 开启按钮加载
          instance.confirmButtonLoading = true;
          // 调用打印页面
          window.location.href = `${IFRAME_URL}iframePrintUnit?id=${row.id}`;
          done();
        } else {
          done();
        }
      },
    }
  ).catch(() => {});
};

function handleIframeMessage(event) {
  // 获取从 Vue 组件发送过来的数据
  const receivedData = event.data;
  returnText.value = receivedData;
  // 在这里处理接收到的数据
  console.log("receivedData", receivedData); // 输出传输过来的数据
}

onMounted(() => {
  getTableList();
  inputAutoFocus();
  getPlantList();
  // 添加iframe监听
  window.addEventListener("message", handleIframeMessage);
});

onBeforeUnmount(() => {
  // 销毁iframe监听
  window.removeEventListener("message", handleIframeMessage);
});
</script>
